<?php

App::import('Vendor', 'invoice');

App::import('Model', 'Note');
$n = new Note();

$notes = array();

$arrange = ($sorting[0][0] == 'member') ? 'left' : 'right';
$by = ($sorting[1][0] == 'member') ? 'Co-Operator' : 'Producer';
$for = ($sorting[0][0] == 'member') ? 'Co-Operator' : 'Producer';
$subtitle = ($sorting[0][0] == 'member') ? 'Invoice' : 'by ' . $by;

$data = array(
	'preferences' => array(
		'by' => $by,
		'desc' => 'Product',
		'for' => $for,
		'subtitle' => $subtitle,
		'contact' => $arrange,
		'2sided' => Configure::read('Invoice.double_side')
	)
);

$invoices = array();
$current = array('sections' => array());
$p = '';
$m = '';
$now = time();
$total = 0;
$r_total = 0;
$i_total = 0;
$t_total = 0;
$subTotal = 0;
$taxTotal = 0;
$surcharge = 0;
$m_fees_total = 0;
$flipper = ($sorting[0][0] == 'member') ? 1 : -1;
$comp = '';
$df = '%B %e, %Y';
foreach ($lines as $line) {
	$comp = $line[$sorting[0][0]][$sorting[0][1]];
	if ($sorting[0][0]=='member') {
		$comp = $line['member']['first_name'] . ' ' . $comp;
	}
	if ($p != $comp) { // we've completed an invoice
		if ($i_total > 0) {
			//echo '<tr><td class="subtotal" colspan="6">' . ucwords($p) . ' Total: $' . number_format($r_total,2) . '</td></tr>' . "\n";
			
			$a_total = 0;
			foreach($notes as $note) {
				$a_total += $note['Note']['adj_amount'] * 100;
			}
			
			if ($sorting[0][0] == 'member') {
			    $surcharge = round(($i_total + $a_total) * (MEMB_SURCHARGE/100))/100;
			} else {
			    $surcharge = $flipper * round(($i_total + $a_total) * (PROD_SURCHARGE/100))/100;
			}
			$inv_total = (($i_total + $a_total)/100) + $surcharge + ($t_total/100);
			$current['totals'] = array(
				'sub' => '$' . number_format($i_total/100,2),
    		'adj' => '$' . number_format($a_total/100,2),
				'surcharge' => '$' . number_format($flipper * $surcharge,2),
				'm_fee' => '$' . number_format($flipper * $m_fee,2),
				'tax' => '$' . number_format($t_total/100,2),
				'final' => '$' . number_format($inv_total + ($flipper * $m_fee),2),
				'message' => $member_message
			);
			$invoices[] = $current;
			$current = array('sections' => array());
			$r_total = 0;
			$i_total = 0;
			$t_total = 0;
		}
		$p = $comp;
		$mtime = strtotime($line[$sorting[0][0]]['paid_fee'] . ' +' . Configure::read('Membership.valid_for'));
		$ptime = strtotime(date('r', $mtime) . ' -' . Configure::read('Membership.ask_for_fee'));
		$due = strftime($df,$mtime);
		$member_message = '';
		if ($now > $mtime) {
			$member_message = 'Your membership fee of $' . $line[$sorting[0][0]]['memb_amt_owed'] . ' is due as of ' . $due . '.  Your total is adjusted below.';
		} else if ($now > $ptime) {
			$member_message = 'Your membership fee of $' . $line[$sorting[0][0]]['memb_amt_owed'] . ' will be due '. $due . '.  Your total is adjusted below, but we can waive it for this invoice if you prefer.';
		}else {
			$member_message = 'Your membership is paid through ' . $due . '.';
		}
		$m_fee = ($now > $ptime) ? $line[$sorting[0][0]]['memb_amt_owed'] : 0;
		$m_fees_total += $m_fee;

		if ($sorting[0][0] == 'member') {
			$current['Member'] = array('first_name' => $line['member']['first_name']);
			$current['Member']['last_name'] = $line['member']['last_name'];
			$current['Member']['address_line1'] = $line['member']['address_line1'];
			$current['Member']['city'] = $line['member']['city'];
			$current['Member']['state'] = $line['member']['state'];
			$current['Member']['zip'] = $line['member']['zip'];
			$current['Member']['home_phone'] = $line['member']['home_phone'];
			$current['Member']['work_phone'] = $line['member']['work_phone'];
			$current['Member']['mobile_phone'] = $line['member']['mobile_phone'];
			$current['Member']['email_address'] = $line['member']['email_address'];
			$notes = $n->getForMember($line['member']['member_id']);
			$current['notes'] = $notes;
		} else {
			
			$mInfo = $this->requestAction('/members/getMemberInfo/' . $line['producer']['member_id']);
			$current['Member'] = array('first_name' => $comp);
			$current['Member']['address_line1'] = $mInfo['Member']['work_address_line1'];
			$current['Member']['city'] = $mInfo['Member']['work_city'];
			$current['Member']['state'] = $mInfo['Member']['work_state'];
			$current['Member']['zip'] = $mInfo['Member']['work_zip'];
			$current['Member']['work_phone'] = $mInfo['Member']['work_phone'];
			$notes = $n->getForProducer($line['product_list']['producer_id']);
			$current['notes'] = $notes;
		}
		
	}
	//calculate weight
	if ($line['basket_items']['weight'] == 0) {
		if ($line['product_list']['random_weight'] != 0) {
			if ($line['product_list']['minimum_weight'] == 0 && $line['product_list']['maximum_weight'] == 0) { // weights should not be averaged
				$line['basket_items']['weight'] = 1;
			} else {
				$line['basket_items']['weight'] = ($line['product_list']['minimum_weight'] + $line['product_list']['maximum_weight']) / 2;
			}
		}
	}
	//calculate total
	$line['subtotal'] = ($line['basket_items']['missing']) ? 0 : $line['orderables']['price'] * $line['basket_items']['quantity'];
	$line['subtotal'] = ($line['basket_items']['weight'] == 0) ? $line['subtotal'] : $line['subtotal'] * $line['basket_items']['weight'];
	$line['tax'] = ($line['product_list']['tax_exempt']) ? 0 : $line['subtotal'] * SALES_TAX;
	$m_comp = ($sorting[1][0] == 'member') ? $line[$sorting[1][0]][$sorting[1][1]] . ', ' . $line['member']['first_name'] : $line[$sorting[1][0]][$sorting[1][1]];
	if (($m != $m_comp) || ($r_total == 0)) {
		$m = ($sorting[1][0] == 'member') ? $line[$sorting[1][0]][$sorting[1][1]] . ', ' . $line['member']['first_name'] : $line[$sorting[1][0]][$sorting[1][1]];
		$current['sections'][$m] = array();
	}
	//echo $sorting[1][0],$sorting[1][1];
	//echo 'BN: '. $line[$sorting[1][0]][$sorting[1][1]];
	//array('desc'=>'Eggs, Medium Brown - Free Range','quantity' => '5','price' => '$2.25/dozen','weight' => 'N/A','tax' => '$0.00','total' => '$11.25'),
	$t_line = array();
	$t_line['desc'] = ($line['basket_items']['missing']) ? '<i>' . $line['product_list']['product_name'] . '</i>' : $line['product_list']['product_name'];
	$t_line['quantity'] = ($line['basket_items']['missing']) ? 0 : $line['basket_items']['quantity'];
	$t_line['price'] = '$' . number_format($line['orderables']['price'],2) . '/' . $line['orderables']['priced_by'];
	$w = ($line['basket_items']['weight'] == 0) ? 'N/A' : number_format($line['basket_items']['weight'],2) . ' ' . $line['orderables']['priced_by'] . '(s)';
	$t_line['weight'] = $w;
	$t_line['tax'] = '$' . number_format($line['tax'],2);
	$t_line['total'] = '$' . number_format($line['subtotal'] + $line['tax'],2);
	
	$current['sections'][$m][] = $t_line;
	$tot = round($line['subtotal']*100);
	$tax = round($line['tax']*100);
	//$total += $line['subtotal'] + $line['tax'];
	$i_total += $tot;
	$t_total += $tax;
	$r_total += ($tot+$tax)/100;
	$subTotal += $tot;
	//$r_total += $line['subtotal'] + $line['tax'];
	$taxTotal += $tax;
}

$a_total = 0;
foreach($notes as $note) {
	$a_total += $note['Note']['adj_amount'] * 100;
}

$extraSpace = false;
if ($sorting[0][0] == 'member') {
    $surcharge = round($i_total * (MEMB_SURCHARGE/100));
} else {
    $surcharge = $flipper * round($i_total * (PROD_SURCHARGE/100));
}
$inv_total = (($i_total + $a_total + $surcharge + $t_total)/100);


$current['totals'] = array(
    'sub' => '$' . number_format($i_total/100,2),
    'surcharge' => '$' . number_format($flipper * $surcharge/100,2),
    'm_fee' => '$' . number_format($flipper * $m_fee,2),
    'adj' => '$' . number_format($a_total/100,2),
    'tax' => '$' . number_format($t_total/100,2),
    'final' => '$' . number_format($inv_total + ($flipper * $m_fee),2),
	'message' => $member_message
);
$invoices[] = $current;

$data['Invoices'] = $invoices;
//echo '<pre>';
//print_r($data);
//echo '</pre>';
//$total += $inv_total;



$I = new InvoicePDF($extraSpace);
$I->run($data);

if (!Configure::read('renderPdfs')) {
	$pdfcode = $I->output(1);
	$pdfcode = r("\n","\n<br>",htmlspecialchars($pdfcode));
	e('<html>');
	e("<body>");
	e('<pre>');
	print_r($data);
	e(trim($pdfcode));
	e(WWW_ROOT);
	e('</pre>');
	e("</body>");
	e('</html>');
} else {
	$I->ezStream(array('Content-Disposition' => 'invoices-' . $sorting[0][0] . '-' . $page . '.pdf'));
}
?>